using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using AdminApiTemplate.Api.Attributes;

namespace AdminApiTemplate.Api.Filters
{
    public class ProcessActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var actionDescriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
            var localApiAttribute = (LocalApiAttribute)actionDescriptor.MethodInfo.GetCustomAttributes(typeof(LocalApiAttribute), true).FirstOrDefault();
            if (localApiAttribute!=null)
            {
                if (!IsLocalRequest(context.HttpContext))
                {
                    context.Result = new NotFoundResult();
                    return;
                }
            }

            base.OnActionExecuting(context);
        }

        private bool IsLocalRequest(HttpContext context)
        {
            byte[] bytes = context.Connection.RemoteIpAddress.GetAddressBytes();
            if (bytes[0] == 0)
            {
                return true;
            }
            else if (bytes[0] == 10)
            {
                return true;
            }
            else if (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
            {
                return true;
            }
            else if (bytes[0] == 192 && bytes[1] == 168)
            {
                return true;
            }
            else if (bytes[0] == 127 && bytes[1] == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
